package com.chengqj.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * Copyright © 2020年 com.qxkj. All rights reserved.
 *
 * @author chengqj
 * 多mongodb数据源配置
 * version 1.0.0 (接口必须带上)
 * @date 2020/11/5 16:43
 */
@Configuration
@EnableMongoRepositories(
        basePackages = "com.chengqj.user",
        mongoTemplateRef = "mongoTemplate")
public class UserMongoConfig {
    @Bean(name = "userMongoProperties")
    @Primary
    @ConfigurationProperties(prefix = "spring.data.mongodb.user")
    public MongoProperties primaryMongoProperties() {
        return new MongoProperties();
    }

    @Primary
    @Bean(name = "mongoTemplate")
    public MongoTemplate primaryMongoTemplate(@Qualifier(value = "userMongoProperties") MongoProperties mongoProperties, @Autowired MappingMongoConverter mappingMongoConverter) {
        return new MongoTemplate(primaryFactory(mongoProperties), mappingMongoConverter);
    }

    @Bean(name = "userMongoDbFactory")
    @Primary
    public MongoDatabaseFactory primaryFactory(MongoProperties mongoProperties) {
        return new SimpleMongoClientDbFactory(mongoProperties.getUri());
    }

}
